<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<!DOCTYPE html>
<html>
<head>
<title>topo</title>
<tags:import includes="jqUI,jqUICss,topo,topoCss,upload,uploadCss,progressBtn,progressBtnCss"></tags:import>

<style type="text/css">
.imgSelected {
	border: green solid 5px;
}

</style>

</head>
<body>
	<div class="jtopo_toolbar">
		<!--<input type="radio" name="modeRadio" value="normal" checked="" id="r1">
		<label for="r1"> 默认</label>&nbsp;<input type="radio" name="modeRadio" value="select" id="r2">
		<label for="r2"> 框选</label>&nbsp;<input type="radio" name="modeRadio" value="drag" id="r3">
		<label for="r3"> 平移</label>&nbsp;<input type="radio" name="modeRadio" value="edit" id="r4">
		<label for="r4"> 编辑</label>&nbsp;&nbsp; -->
		<button class="btn gray" id="save" onclick="saveTopo();"><i class="icon-save"></i> </button>
		<button class="btn gray" id="zoomOutButton"><i class="icon-zoom-in"></i></button>
		<button class="btn gray" id="zoomInButton" ><i class="icon-zoom-out"></i></button>
		<button class="btn gray" id="centerButton"><i class="icon-check-empty"></i></button>
		<input type="text" id="findText" value=""  placeholder="输入站点名称" onkeydown="findButton.click()">		
		<button class="btn gray" id="findButton"><i class="icon-search"></i></button>
		<button class="btn gray" id="exportButton"><i class="icon-file"></i></button>
		<button class="btn gray" id="changeBackground"><i class="icon-camera-retro"></i></button>
		
		<!-- <input type="button" id="fullScreenButton" value="全屏显示"> 
		<input type="checkbox" id="zoomCheckbox">
		<label for="zoomCheckbox">鼠标缩放</label>&nbsp;&nbsp;-->
	<canvas id="canvas" width="900px" height="600px" style="padding-top: 5px"></canvas>
	
	<ul id="contextmenu" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
		<li><a onclick="add=false;detialNode();netTopo.hideMenu();">详情</a></li>
		<li><a onclick="deleteElement();netTopo.hideMenu();">删除</a></li>
	</ul>
	
	<ul id="contextmenu1" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
		<li><a onclick="add=true;showAddNode();netTopo.hideMenu();">添加节点</a></li>
		<li><a onclick="add=true;showAddLink();netTopo.hideMenu();">添加连线</a></li>
	</ul>
	
	<div id="dialog-showbackground" class="hide" >
		<div>
			<span class="btn btn-success fileinput-button">
		        <i class="glyphicon glyphicon-plus"></i>
		        <span>选择图片</span>
		        <input id="fileupload" type="file" name="files[]" multiple>
		    </span>
		    <button id="uploadAction" class="btn button test"  data-color="#0DB8DF"  data-opacity="0.9"  type="reset">
				<i class="icon-upload bigger-110"></i>上传
			</button>
		</div>
		<div class="hr hr-12 hr-double"></div>
		<p>
			请选择背景图片
		</p>
		<div class="hr hr-12 hr-double"></div>
		<div id="backgroundSelect">
			<img id="bg" onclick="selectImg(this)" src="/webems/static/modules/topo/images/bg.png" width="80px" height="80px">
			<img id="nodeOn" onclick="selectImg(this)" src="/webems/static/modules/topo/images/nodeOn.png" width="80px" height="80px">
		</div>
	</div>
	
	<div id="dialog-addNode" class="hide" >
        <label class="control-label" for="form-field-5">名称： </label>
    	<input class="span1" type="text" id="form-field-5" />
    	<br/>
        <!-- <label class="control-label" for="form-field-5">详细说明： </label>
       	<input class="span1" type="text" id="form-field-5" /> -->
       	<label class="control-label" for="form-field-5">启用： </label>
       	<input type="checkbox" class="ace" name="enable"/> 
       	<span class="lbl"></span>
	</div>
	
	<div id="dialog-addLink" class="hide" >
        <label class="control-label" for="form-field-5">源： </label>
    	<select class="small m-wrap" tabindex="1">
			
		</select>
		<br/>
        <label class="control-label" for="form-field-5">宿： </label>
       	<select class="small m-wrap" tabindex="1">
			
		</select>
	</div>
	
	<script type="text/javascript">
function parseMessage(message){
	console.log(message);
}


var _content = '${content}';
var topoObj;
if(!_content){
	topoObj = {'id':0,'background':'/webems/static/modules/topo/images/bg.png','nodes':[],'links':[]};
}else{
	topoObj = eval('(${content})');
}
//init
var canvas = document.getElementById('canvas');
var netTopo = new EmsTopo(canvas,topoObj);
netTopo.showTopo();

//autocomplete
var data;
var freshAutoData = function(){
	data = [];
	for(var i=0; i < netTopo.nodes.length; i++){
		var n = netTopo.nodes[i];
		data.push({label: n.text, category: "" });
	}
	$( "#findText" ).catcomplete({
		delay: 0,
		source: data
	});
};
freshAutoData();

//right menu
var menuTarget;
function showRightMenu(event, show){
	var menu = document.getElementById('contextmenu');
	var width = $('#contextmenu').css('width');
	var height = $('#contextmenu').css('height');
	if(show){
		menuTarget = event.target;
		var rightedge = document.body.clientWidth-event.clientX;
		var bottomedge = document.body.clientHeight-event.clientY;
		if (rightedge < width){
			menu.style.posLeft= document.body.scrollLeft + event.clientX - width ;
		}else{
			menu.style.posLeft= document.body.scrollLeft + event.clientX;
		}
		if(bottomedge < height){
			menu.style.posTop= document.body.scrollTop + event.clientY - heigth ;
		}else{
			menu.style.posTop= document.body.scrollTop + event.clientY;
		}
		
		$('#contextmenu').show('fast');
	}else{
		$('#contextmenu').hide();
	}
}

function showRightMenu1(event, show){
	var menu = document.getElementById('contextmenu1');
	var width = $('#contextmenu1').css('width');
	var height = $('#contextmenu1').css('height');
	if(show){
		var rightedge = document.body.clientWidth-event.clientX;
		var bottomedge = document.body.clientHeight-event.clientY;
		if (rightedge < width){
			menu.style.posLeft= document.body.scrollLeft + event.clientX - width ;
		}else{
			menu.style.posLeft= document.body.scrollLeft + event.clientX;
		}
		if(bottomedge < height){
			menu.style.posTop= document.body.scrollTop + event.clientY - heigth ;
		}else{
			menu.style.posTop= document.body.scrollTop + event.clientY;
		}
		$('#contextmenu1').show('fast');
	}else{
		$('#contextmenu1').hide();
	}
}

//update background
var fileUpLoad = $('#fileupload').fileupload({
    autoUpload: true,//是否自动上传
    url: "upload",//上传地址
    dataType: 'json',
    add : function(e, data){
    	$('#uploadAction').click(function(){
    		$(this).text('上传中……');
    		data.submit();
    	});
    },
    done: function (e, data) {//设置文件上传完毕事件的回调函数
        $.each(data.result.files, function (index, file) {//
        	$('#uploadAction').text('上传');
        });
    }
});

//change background
$( "#changeBackground" ).on('click', function(e) {
	e.preventDefault();

	var dialog = $( "#dialog-showbackground" ).removeClass('hide').dialog({
		modal: true,
		title: "更换背景",
		title_html: true,
		buttons: [ 
			{
				text: "取消",
				click: function() {
					$( this ).dialog( "close" ); 
				} 
			},
			{
				text: "确定",
				click: function() {
					netTopo.setBackground(getSelectImgSrc());
					$( this ).dialog( "close" ); 
				} 
			}
		]
	});
	
	var btns = $('.ui-dialog-buttonset').find('button');
	btns.removeClass();
	btns.addClass('btn btn-info');
});

function getSelectImgSrc(){
	var imgs = $('#backgroundSelect').find('img');
	var ret = '';
	imgs.each(function(a,b){
		if($(b).attr('class')=='imgSelected'){
			ret = (b.src);
		}
	});
	return ret;
}

function selectImg(ele){
	var imgs = $('#backgroundSelect').find('img');
	imgs.removeClass('imgSelected');
	$(ele).addClass('imgSelected');
}

selectImg(document.getElementById('bg'));


//overide menu function
netTopo.hideMenu = function(){
	showRightMenu(null,false);
	showRightMenu1(null,false);
};

netTopo.showGroupMenu = function(e){
	showRightMenu(e,true);
};

netTopo.showLinkMenu = function(e){
	showRightMenu(e,true);
};

netTopo.showSceneMenu = function(e){
	showRightMenu1(e,true);
};

// delete 
function deleteElement(){
	var id = menuTarget._id;
	var type = menuTarget.elementType;
	if(type == 'node'){
		$.ajax({
			url:'/webems/cfg/site/delete/'+id,
			success:function(data){
				if (data != undefined && data.result != 0) {
					/* netTopo.delNodeById(id); */
				}else{
					parent.commonAPI.warn('错误',data.message);
				}
			},
			failure:function(res){
				parent.commonAPI.warn('错误','请联系系统管理员。');
			}
		});
		
	}else{
		netTopo.delLinkById(id);
	}
}

//show add
var countId = 1;
var add = true;
function showAddNode(){
	var btns = [ 
				{
					text: '取消',
					click: function() {
						$( this ).dialog( 'close' ); 
					} 
				},
				{
					text: '确定',
					click: function() {
						if(!add){
							$( this ).dialog( "close" ); 
							return;
						}
							
						var formValue = $(this).find('input[type=text]');
						var name = formValue[0].value;
						//var info = formValue[1].value;
						if(!name || !name.trim()){
							alert('不能为空');
						}else{
							
							$.ajax({
								url:'/webems/cfg/site/create',
								data:{sname:name},
								type:'POST',
								success:function(res){
									if (data != undefined && data.result != 0) {
										
									}else{
										parent.commonAPI.warn('错误',data.message);
									}
									/* var _id = res;
									var mynode = new MyNode({id:_id,text:name,type:NodeGlobal.group,x:0, y:0, alarmLevel:-1,alarmInfo:''});
									var n = netTopo.addNode(mynode);
									freshAutoData(); */
								},
								failure:function(){
									parent.commonAPI.warn('错误','请联系系统管理员。');
								}
							});
							
							$( this ).dialog( 'close' ); 
							
						}
						
					} 
				}
			];
	var dialog = $( '#dialog-addNode' ).removeClass('hide').dialog({
		modal: true,
		title: add?'添加节点':'查看节点',
		title_html: true,
		buttons: add?btns:[],
		close:function(){
			$(this).find('input[type=text]').val('');
		}
	});
	
	var btns = $('.ui-dialog-buttonset').find('button');
	btns.removeClass();
	btns.addClass('btn btn-info');
}

function showAddLink(){
	var dialog = $( '#dialog-addLink' ).removeClass('hide').dialog({
		modal: true,
		title: add?'添加连接线':'查看连接线',
		title_html: true,
		buttons: [ 
			{
				text: '取消',
				click: function() {
					$( this ).dialog( 'close' ); 
				} 
			},
			{
				text: '确定',
				click: function() {
					if(!add){
						$( this ).dialog( 'close' ); 
						return;
					}
					
					var formValue = $(this).find('select');
					var srcNode = formValue[0].value;
					var destNode = formValue[1].value;
					if(!srcNode|| !destNode){
						alert('不能为空');
					}else if(srcNode == destNode){
						alert('不能相同');
					}else{
						var mylink = new MyLink({fromId:srcNode,toId:destNode});
						netTopo.addLink(mylink);
						$( this ).dialog( 'close' ); 
					}
					
				} 
			}
		]
	});
	
	$('#dialog-addLink').find('select').html('');
	for(var i=0; i<netTopo.nodes.length; i++){
		var _n = netTopo.nodes[i];
		var value = _n._id;
		var text = _n.text;
		$('#dialog-addLink').find('select').append($('<option value="'+value+'">'+text+'</option>'));
	}
	var btns = $('.ui-dialog-buttonset').find('button');
	btns.removeClass();
	btns.addClass('btn btn-info');
}

function detialNode(){
	if(menuTarget.elementType == 'node'){
		showAddNode();
		var text = menuTarget.text;
		var inputs = $( '#dialog-addNode' ).find('input[type=text]');
		inputs.eq(0).val(text);
	}else{
		showAddLink();
		var fromId = menuTarget.nodeA._id;
		var toId = menuTarget.nodeZ._id;
		var inputs = $( '#dialog-addLink' ).find('select');
		inputs.eq(0).val(fromId);
		inputs.eq(1).val(toId);
	}
}

function saveTopo(){
	var content = netTopo.toJson();
	var id = 0;
	var url = '/webems/topo/save';
	$.ajax({
		url:url,
		data:{topoId:id, content:JSON.stringify(content)},
		type:'POST',
		success : function(response){
			console.log(response);
		},
		failure : function(response){
			console.log(response);
		}
	});
}

/**
 * 网络图接收Server推送过来的消息 网元告警与站点增删 
 */
function receiveMessage(data){
	//console.log(['topoIndex receive the message',data]);
	var type = data.type;
	var action = data.action;
	
	if(action == 'on'){
		if(type == 'alarmNe'){
			addAlarm(data.entity);
		}else if(type == 'createSite'){
			addSite(data.entity);
		}
	}else if(action=='off'){
		if(type == 'alarmNe'){
			delAlarm(data.entity);
		}else if(type == 'createSite'){
			delSite(data.entity);
		}
	}
}

/** 
 * 告警产生时，在本拓扑上查找该告警所在的Site,然后将告警个数显示在topo上 
 */
function addAlarm(entity){
	var level = entity.severity.id;
	if(level==10){
		level = -1;
	}
	var siteId = entity.nenode.site.sid;
	
	var theSite = netTopo.getNodeById(siteId);
	var alarmLevelArr = theSite.alarmLevelArr;
	var alarmInfoArr = theSite.alarmInfoArr;
	var has = false;
	for(var i=0; i<alarmLevelArr.length; i++){
		if(level == alarmLevelArr[i]){
			alarmInfoArr[i] = (alarmInfoArr[i] + 1);
			has = true;
			break;
		}
	}
	if(!has){
		if(alarmLevelArr.length==0 || level<alarmLevelArr[0] ){
			//在数组前面加上该告警
			alarmLevelArr.unshift(level);
			alarmInfoArr.unshift(1);
		}else{
			//在数组后面加上该告警 
			alarmLevelArr.push(level);
			alarmInfoArr.push(1);
		}
		theSite.alarmLevelArr = alarmLevelArr;
		theSite.alarmInfoArr = alarmInfoArr;
	}

	netTopo.setAlarm(theSite); 
}

function delAlarm(entity){
	var level = entity.severity.id;
	if(level==10){
		level = -1;
	}
	var siteId = entity.nenode.site.sid;
	var theSite = netTopo.getNodeById(siteId);
	var alarmLevelArr = theSite.alarmLevelArr;
	var alarmInfoArr = theSite.alarmInfoArr;
	
	var index = -1;
	for(var i=0; i<alarmLevelArr.length; i++){
		if(level == alarmLevelArr[i]){
			alarmInfoArr[i] = (alarmInfoArr[i] - 1);
			if(alarmInfoArr[i] == 0){
				index = i;
				break;
			}
		}
	};
	
	if(index != -1){
		alarmLevelArr.splice(index,1);
		alarmInfoArr.splice(index,1);
	}
	theSite.alarmLevelArr = alarmLevelArr;
	theSite.alarmInfoArr = alarmInfoArr;
	
	netTopo.setAlarm(theSite);
}

function addSite(entity){
	var _id = entity.sid;
	var name = entity.sname;
	var mynode = new MyNode({id:_id,text:name,type:NodeGlobal.group,x:0, y:0, alarmLevel:-1,alarmInfo:''});
	var n = netTopo.addNode(mynode);
	freshAutoData();
}
function delSite(entity){
	var _id = entity.sid;
	netTopo.delNodeById(_id);
}
$(function(){
	$('html').attr('style','overflow-x:scroll;overflow-y:scroll;');
});
</script>
</body>
</html>